package cn.iocoder.yudao.module.system.controller.admin.a_pictures;

import cn.hutool.core.io.FileUtil;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.module.system.controller.admin.a_pictures.vo.*;
import cn.iocoder.yudao.module.system.dal.dataobject.a_pictures.PicturesDO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.service.a_ids.IdsService;
import cn.iocoder.yudao.module.system.service.a_pictures.ImageUploadServiceImpl;
import cn.iocoder.yudao.module.system.service.a_pictures.PicturesService;
import cn.iocoder.yudao.module.system.service.ivrs.IvrsService;
import cn.iocoder.yudao.module.system.service.user.AdminUserService;
import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.nacos.common.utils.UuidUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.annotation.security.PermitAll;
import javax.validation.Valid;

import java.util.HashMap;
import java.util.Map;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;


@Tag(name = "管理后台 - 稿件管理 - 图片")
@RestController
@RequestMapping("/system/pictures")
@Validated
public class PicturesController {

    @Resource
    private PicturesService picturesService;

    @Resource
    ImageUploadServiceImpl imageUploadService;

    @Resource
    private AdminUserService adminService;

    @Resource
    private IdsService idsService;

    @Resource
    IvrsService ivrsService;


    @Value("${fileData.picturePath}")
    private String imagePath;

    @GetMapping("/select/page")
    @Operation(summary = "获得图片分页")
    @PreAuthorize("@ss.hasPermission('system:pictures:query')")
    public CommonResult<PageResult<PicturesDO>> selectPage(@Valid PicturesPageReqVO pageVO) {
        PageResult<PicturesDO> pageResult = picturesService.selectPage(pageVO);
        return success(pageResult);
    }

    @PostMapping("/create")
    @Operation(summary = "新增图片")
    @PreAuthorize("@ss.hasPermission('system:pictures:create')")
    public Map<String, String> create(@Valid @RequestBody PicturesReqVO createReqVO) {
        String id = picturesService.insertHybaseByImg(createReqVO);
        Map<String, String> map = new HashMap<>();
        map.put("id", id);
        return map;
    }

    @PutMapping("save")
    @Operation(summary = "图片保存")
    @PreAuthorize("@ss.hasPermission('system:pictures:create')")
    public CommonResult<String> save(@Valid PicturesBaseVO picturesDO) {
        String id = picturesService.save(picturesDO);
        if (id != null && StringUtils.isNotBlank(id) ) {
            return CommonResult.success(id);
        } else {
            return error(5000,"图片添加失败！");
        }
    }

    @DeleteMapping("/deleteAndHybase")
    @Operation(summary = "删除数据库和海贝图片")
    @PreAuthorize("@ss.hasPermission('system:pictures:delete')")
    public CommonResult<Boolean> deleteAndHybase(@RequestBody Long[] ids) {
        return CommonResult.success(picturesService.delete(ids));
    }

    @GetMapping("/page")
    @Operation(summary = "获得图片分页")
    @PreAuthorize("@ss.hasPermission('system:pictures:query')")
    public CommonResult<PageResult<PicturesPageReqVO>> getPage(@Valid PicturesPageReqVO pageVO) {
        PageResult<PicturesPageReqVO> pageResult = picturesService.getPage(pageVO);
        return success(pageResult);
    }

    @DeleteMapping("/delete")
    @Operation(summary = "删除图片")
    @Parameter(name = "id", description = "编号", required = true)
    @PreAuthorize("@ss.hasPermission('system:pictures:delete')")
    public CommonResult<String> delete(@RequestParam("ids") String ids, @RequestParam("urls") String urls) {
        if (picturesService.delete(ids, urls)) {
            return success("删除成功");
        } else {
            return success("删除失败");
        }
    }

    @GetMapping("/getInfo")
    @Operation(summary = "获得图片详情")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:pictures:query')")
    public CommonResult<PicturesDO> getInfo(@RequestParam("id") String id) {
        return success(picturesService.getInfo(id));
    }

    @GetMapping("/get")
    @Operation(summary = "获得图片")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:pictures:query')")
    public CommonResult<PicturesReqVO> get(@RequestParam("id") String id) {
        PicturesReqVO picturesReqVO = picturesService.get(id);
        return success(picturesReqVO);
    }

    @PutMapping("/update")
    @Operation(summary = "更新图片")
    @PreAuthorize("@ss.hasPermission('system:pictures:update')")
    public CommonResult<String> update(@Valid @RequestBody PicturesReqVO updateReqVO) {
        if (StringUtils.isNotBlank(updateReqVO.getId())) {
            if (picturesService.update(updateReqVO)) {
                return success("修改成功");
            } else {
                return success("修改失败");
            }
        }
        return success("修改失败，id为空");
    }

    /**
     * 图片下载计数器
     */
    @GetMapping("/download/count")
    @Operation(summary = "图片下载计数器")
    @PermitAll
    public CommonResult<Object> downloadCount(@RequestParam("id") String id) {
        return success(picturesService.downloadCount(id));
    }


    @PostMapping("/updateReview")
    @Operation(summary = "提交审核")
    @PreAuthorize("@ss.hasPermission('system:pictures:update')")
    public CommonResult<Boolean> updateReview(@RequestParam("id") String id) {
        return success(picturesService.updateReview(id, 1));
    }


    /**
     * 图像检索-- 以图搜图
     * show_num ：返回的结果数量, 最高是10000
     * thresh： 检索粗特征的阈值
     *
     * @return
     */
    @PostMapping("/irsImageFile")
    @Operation(summary = "以图搜图")
    @PreAuthorize("@ss.hasPermission('system:pictures:update')")
    public CommonResult<PageResult<PicturesPageReqVO>> irsImageFile(@RequestParam("file") MultipartFile multipartFile) {
        PicturesPageReqVO picturesPageReqVO = new PicturesPageReqVO();
        picturesPageReqVO.setPageNum(1L);
        picturesPageReqVO.setPageSize(10);
        PageResult<PicturesPageReqVO> features = picturesService.getPageByFeature(picturesPageReqVO, multipartFile);
        return success(features);
    }

    @PostMapping("/updateShare")
    @Operation(summary = "共享素材")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Boolean> updateShare(@RequestParam("id") String id, @RequestParam("shareStatus") String shareStatus) {
        return success(picturesService.updateShare(id, shareStatus));
    }

    @PostMapping("/updatePush")
    @Operation(summary = "推送资源库")
    @PreAuthorize("@ss.hasPermission('system:article:update')")
    public CommonResult<Boolean> updatePush(@RequestParam("id") String id, @RequestParam("pushStatus") String pushStatus) {
        return success(picturesService.updatePush(id, pushStatus));
    }

    @GetMapping("/pageQukan")
    @Operation(summary = "获得图片分页-趣看")
    @PermitAll
    public CommonResult<PageResult<PicturesPageQukanReqVO>> getPageQukan(@RequestHeader Map<String, String> headers, @Valid PicturesPageQukanReqVO pageVO) {
        String userName = idsService.getUserName(headers.get("trsidsssosessionid"));
        if (StringUtils.isEmpty(userName)) {
            return error(200, "当前用户不存在");
        }
        AdminUserDO userByUsername = adminService.getUserByUsername(userName);
        if (userByUsername.getId() == null) {
            return error(200, "当前用户不存在");
        }
        PageResult<PicturesPageQukanReqVO> pageResult = picturesService.getPageQukan(pageVO, userByUsername.getId());
        return success(pageResult);
    }

    @GetMapping("/getQukan")
    @Operation(summary = "获取图片详情-趣看")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PermitAll
    public CommonResult<PicturesReqVO> getQukan(@RequestHeader Map<String, String> headers, @RequestParam("id") String id) {
        String userName = idsService.getUserName(headers.get("trsidsssosessionid"));
        if (StringUtils.isEmpty(userName)) {
            return error(200, "当前用户不存在");
        }
        PicturesReqVO picturesReqVO = picturesService.get(id);
        return success(picturesReqVO);
    }

    @PostMapping("matting/human")
    @Operation(summary = "智能抠图")
    @OperateLog(enable = false)
    public CommonResult<String> mattingHuman(@RequestParam String image) {
        String uuid = UuidUtils.generateUuid();
        String ext = FileUtil.getSuffix(image);
        ivrsService.mattingHuman(image, imagePath + "/" + uuid + "." + ext);
        return success(imagePath + "/" + uuid + "." + ext);
    }

    @PostMapping("upload")
    @Operation(summary = "图片上传")
    @PreAuthorize("@ss.hasPermission('system:pictures:create')")
    public CommonResult<ImageRespVO> upload(@RequestParam("file") MultipartFile file) {
        return CommonResult.success(imageUploadService.upload(file));
    }

    /**
     * 通过图片ID获得图片的下载路径
     */
    @Transactional
    @GetMapping("/getImageDownloadPath")
    @Operation(summary = "通过图片ID获得图片的下载路径")
    @Parameter(name = "id", description = "编号", required = true, example = "1024")
    @PreAuthorize("@ss.hasPermission('system:pictures:query')")
    public CommonResult<String> getImagePath(@RequestParam("id") String id) {
        /**
         *对应id图片的"pictures_download_num"字段值加1
         */
        picturesService.downloadCount(id);
        return success(picturesService.getImageDownloadPath(id));
    }
}
